package business;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import orm.AORef;
import orm.ChildrenBehaviorPurpose;
import orm.CollectivityClass;
import orm.CollectivityMonthArrange;
import orm.CollectivityMonthDomain;
import orm.CollectivityMonthDomainAim;
import orm.CollectivityMonthWeekAim;
import orm.CollectivityTeachingPlan;
import orm.CollectivityTeachingPlanMonth;
import orm.CollectivityTeachingPlanWeek;
import orm.CollectivityWeekArrange;
import orm.CollectivityWeekTimeBucket;
import orm.IndividualClass;
import orm.IndividualTeachingPlan;
import orm.Teacher;
import orm.TeachingPlanBaseInfo;
import orm.TopicTransferModel;
import dao.AORefDAO;
import dao.CMonthArrangeDAO;
import dao.CMonthDomainAimDAO;
import dao.CMonthDomainDAO;
import dao.CMonthWeekAimDAO;
import dao.CTeachingPlanMonthDAO;
import dao.CTeachingPlanWeekDAO;
import dao.CWeekArrangeDAO;
import dao.CWeekTimeBucketDAO;
import dao.ChildrenBehaviorPurposeDAO;
import dao.CollectivityClassDAO;
import dao.CollectivityTeachingPlanDAO;
import dao.IndividualTeachingPlanDAO;
import dao.StudentDAO;
import dao.TeacherDAO;
import dao.TeachingPlanBaseInfoDAO;
import dao.UserCollectionDAO;

import util.DBHelper;
import util.Utility;
import util.WebConstants;

public class CTeachingPlanMonthInfoServlet extends BaseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public CTeachingPlanMonthInfoServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String strFunc = request.getParameter("func");
		Connection con = null;
		Statement stmt = null;
		if (strFunc.equals("load")) {
			gotoCTPMInfo(request, response);
			request.getRequestDispatcher("../" + Utility.JSP_CTeachingPlanMonthInfo).forward(request, response);
		} else if (strFunc.equals("edit")) {
			String strCMonthArrangeID = request.getParameter("cMonthArrangeID");
			CollectivityMonthWeekAim[] cmwa = null;
			
			CTeachingPlanMonthDAO ctpmDAO = new CTeachingPlanMonthDAO();
			CMonthDomainDAO cmdDAO = new CMonthDomainDAO();
			CMonthDomainAimDAO cmdaDAO = new CMonthDomainAimDAO();
			CMonthArrangeDAO cmaDAO = new CMonthArrangeDAO();
			CMonthWeekAimDAO cmwaDAO = new CMonthWeekAimDAO();
			TeachingPlanBaseInfoDAO tpbiDAO = new TeachingPlanBaseInfoDAO();
			
			try {
				CollectivityTeachingPlanMonth ctpm = ctpmDAO.getCTPMonthByCMAID(strCMonthArrangeID);
				ArrayList<CollectivityMonthDomain> alCMD = cmdDAO.getCMDByCMAID(strCMonthArrangeID);
				ArrayList<CollectivityMonthDomainAim> alCMDA = cmdaDAO.getcmdaByCWAID(strCMonthArrangeID);
				ArrayList<CollectivityMonthArrange> alCMA = cmaDAO.getcmaBycmaID(strCMonthArrangeID);
				ArrayList<CollectivityMonthWeekAim> alCMWA = cmwaDAO.getcmwaByCWAID(strCMonthArrangeID);
				ArrayList<TeachingPlanBaseInfo> alMonthThemeName = tpbiDAO.getMonthThemeNameByTPProperty();
				ArrayList<TeachingPlanBaseInfo> alWeekThemeName = tpbiDAO.getWeekThemeNameByTPProperty();
				
				String strCWeekArrangeID = "";
				String tpid = null;
				cmwa = new CollectivityMonthWeekAim[alCMWA.size()];
				for(int k = 0; k < alCMWA.size(); k++){
					String cWeekArrangeID = "";
					strCWeekArrangeID = alCMWA.get(k).getCWeekArrangeID();
					String[] alCWeekArrangeID = strCWeekArrangeID.split(",");
					if(alCWeekArrangeID != null){
						for(int m = 0;m < alCWeekArrangeID.length; m++){
							tpid = alCWeekArrangeID[m];
							String temp = tpbiDAO.getThemeActivityNameByTPID(tpid);
							if(temp != null && !temp.equals("")){
								if(!cWeekArrangeID.equals("")){
									cWeekArrangeID+=",";
								}
								cWeekArrangeID += temp;
							}
						}
					}
					cmwa[k] = new CollectivityMonthWeekAim();
					cmwa[k].setCWeekArrangeIDName(cWeekArrangeID);
				}
				
				request.setAttribute("CTPM", ctpm);
				request.setAttribute("CMDArr", alCMD);
				request.setAttribute("CMDAArr", alCMDA);
				request.setAttribute("CMAArr", alCMA);
				request.setAttribute("CMWAArr", alCMWA);
				request.setAttribute("CMWANames", cmwa);
				request.setAttribute("MonthThemeNameArr", alMonthThemeName);
				request.setAttribute("WeekThemeNameArr", alWeekThemeName);
					
				request.getRequestDispatcher("../" + 
							Utility.JSP_CTPMonthArrangeEdit).forward(request, response);
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else if (strFunc.equals("delete")) {
			String cMonthArrangeID = request.getParameter("cMonthArrangeID");
			String strTPID = request.getParameter("hdTPID");
			try {
				con = DBHelper.getConnection();
				con.setAutoCommit(false);
				stmt = con.createStatement();
				
				CTeachingPlanMonthDAO ctpmDAO = new CTeachingPlanMonthDAO();
				CMonthDomainDAO cmdDAO = new CMonthDomainDAO();
				CMonthDomainAimDAO cmdaDAO = new CMonthDomainAimDAO();
				CMonthArrangeDAO cmaDAO = new CMonthArrangeDAO();
				CMonthWeekAimDAO cmwaDAO = new CMonthWeekAimDAO();
				
				ctpmDAO.deleteCTPMonth(stmt, cMonthArrangeID);
				cmdDAO.deleteCMonthDomain(stmt, cMonthArrangeID);
				cmdaDAO.deleteCMonthDomainAim(stmt, cMonthArrangeID);
				cmaDAO.deleteCMonthArrange(stmt, cMonthArrangeID);
				cmwaDAO.deleteCMonthWeekAim(stmt, cMonthArrangeID);
				
				con.commit();
				stmt.close();
				
				gotoCTPMInfo(request, response);
				request.getRequestDispatcher("../" + Utility.JSP_CTeachingPlanMonthInfo).forward(request, response);
				
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
				try {
					con.rollback();
				} catch (SQLException ee) {
					ee.printStackTrace();
				}
			} 
		} else if (strFunc.equals("paging")) {
			com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
			
			Integer teacherID = teacher.getTeacherId();
			int PageSize = Utility.PageSize;
			String strSub = request.getParameter("sub");
			String tmp = request.getParameter("HDPageNo");
			int nPageNo = Integer.parseInt(tmp); 
			String monthThemeName = null;
			String executionDate = null;
			
			if(request.getParameter("MonthThemeName") != null && !request.getParameter("MonthThemeName").equals("")){
				monthThemeName = request.getParameter("MonthThemeName");
			}
			if(request.getParameter("ExecutionDate") != null && !request.getParameter("ExecutionDate").equals("")){
				executionDate = request.getParameter("ExecutionDate");
				
			}
			
			CTeachingPlanMonthDAO ctpmDAO = new CTeachingPlanMonthDAO();
			CollectivityTeachingPlanMonth ctpm = null;
			
			try {
				ArrayList al = ctpmDAO.getSearchCondition(monthThemeName, executionDate, teacherID);
				int totalPage = 0;
				if (al.size() % PageSize == 0) {
					totalPage = al.size()/PageSize;
					request.setAttribute("totalPage",totalPage);
				} else {
					totalPage = (al.size()/PageSize) + 1;
					request.setAttribute("totalPage",totalPage);
				}
				
				if (strSub == null)
				{
					
				} else if (strSub.equals("start")) {
					nPageNo = 1;
				} else if (strSub.equals("front")) {
					nPageNo--;
				} else if (strSub.equals("next")) {
					nPageNo++;
				} else if (strSub.equals("last")) {
					nPageNo = totalPage ;
				} 
				request.setAttribute("pageNo", nPageNo);
				al = new ArrayList<CollectivityTeachingPlanMonth>();
				ListIterator<CollectivityTeachingPlanMonth> it = ctpmDAO.getSearchCondition(monthThemeName, executionDate, teacherID).listIterator();
				int ii = 0;
				while (it.hasNext()) {
					ii++;
					CollectivityTeachingPlanMonth t = it.next();
					if (ii <= PageSize * (nPageNo - 1))
						continue;
					
					ctpm = new CollectivityTeachingPlanMonth();
					ctpm.setCMonthArrangeID(t.getCMonthArrangeID());
					ctpm.setMonthThemeName(t.getMonthThemeName());
					ctpm.setConstitutor(t.getConstitutor());
					ctpm.setClassID(t.getClassID());
					ctpm.setPushDateStart(t.getPushDateStart());
					ctpm.setPushDateEnd(t.getPushDateEnd());
					
					al.add(ctpm);
					
					if(ii > PageSize * nPageNo - 1 ) {
						break;
					}
				}
				request.setAttribute("CTPMList", al);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../" + Utility.JSP_CTeachingPlanMonthInfo).forward(request, response);
			
		} else if (strFunc.equals("searchPage")) {
			com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
			
			Integer teacherID = teacher.getTeacherId();
			int PageSize = Utility.PageSize;
			String strSub = request.getParameter("sub");
			String tmp = request.getParameter("PageNo");
			int nPageNo = Integer.parseInt(tmp);
			String monthThemeName = null;
			String executionDate = null;
			
			if(request.getParameter("MonthThemeName") != null && !request.getParameter("MonthThemeName").equals("")){
				monthThemeName = request.getParameter("MonthThemeName");
			}
			if(request.getParameter("ExecutionDate") != null && !request.getParameter("ExecutionDate").equals("")){
				executionDate = request.getParameter("ExecutionDate");
				
			}

			CTeachingPlanMonthDAO ctpmDAO = new CTeachingPlanMonthDAO();
			try {
				ArrayList al = ctpmDAO.getSearchCondition(monthThemeName, executionDate, teacherID);
				int totalPage = 0;
				if (al.size() % PageSize == 0) {
					request.setAttribute("totalPage",al.size()/PageSize);
				} else {
					request.setAttribute("totalPage",(al.size()/PageSize) + 1);
				}
				
				request.setAttribute("pageNo", nPageNo);
				al = new ArrayList<CollectivityTeachingPlanMonth>();
				ListIterator<CollectivityTeachingPlanMonth> it = ctpmDAO.getSearchCondition(monthThemeName, executionDate, teacherID).listIterator();
				int ii = 0;
				while (it.hasNext()) {
					ii++;
					CollectivityTeachingPlanMonth t = it.next();
					if (ii <= PageSize * (nPageNo - 1))
						continue;
					
					CollectivityTeachingPlanMonth ctpm = new CollectivityTeachingPlanMonth();
					ctpm.setCMonthArrangeID(t.getCMonthArrangeID());
					ctpm.setMonthThemeName(t.getMonthThemeName());
					ctpm.setConstitutor(t.getConstitutor());
					ctpm.setClassID(t.getClassID());
					ctpm.setPushDateStart(t.getPushDateStart());
					ctpm.setPushDateEnd(t.getPushDateEnd());
					
					al.add(ctpm);
					
					if(ii > PageSize * nPageNo - 1 ) {
						break;
					}
				}
				
				request.setAttribute("CTPMList", al);	
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../" + Utility.JSP_CTeachingPlanMonthInfo).forward(request, response);
		} else if (strFunc.equals("showNetwork")) {
			String strCMonthArrangeID = request.getParameter("cMonthArrangeID");
			CWeekArrangeDAO cwaDAO = new CWeekArrangeDAO();
			CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
			CMonthWeekAimDAO cmwaDAO = new CMonthWeekAimDAO();
			CTeachingPlanMonthDAO ctpmDAO = new CTeachingPlanMonthDAO();
			try {
				for(int weekID =1; weekID < 5; weekID++){
				List<TopicTransferModel> models = cwaDAO.queryTopicModels(cmwaDAO.getTPIDSSByCMonthArrangeID(strCMonthArrangeID, weekID));
				Map<Integer,List<String>> developmentDomainActivityMapping = new HashMap<Integer,List<String>>();
				for(TopicTransferModel t : models){
					List<String> temp = developmentDomainActivityMapping.get(t.getDevelopmentDomain());
					if(temp==null){
						developmentDomainActivityMapping.put(t.getDevelopmentDomain(), temp=new ArrayList<String>());
					}
					temp.add(t.getActiveName());
				}
				
				CollectivityTeachingPlanMonth ctpm = ctpmDAO.getCTPMNetByCMAID(strCMonthArrangeID);
				request.setAttribute("developmentDomainActivityMapping"+weekID, developmentDomainActivityMapping);
				request.setAttribute("CTPMArr", ctpm);
				request.setAttribute("CMonthArrangeID", strCMonthArrangeID);
				}
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../" + Utility.JSP_CTPMonthNetwork).forward(request, response);
		} else if (strFunc.equals("SearchCondition")) {
			com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
			
			Integer teacherID = teacher.getTeacherId();
			CollectivityTeachingPlanMonth ctpm = null;
			CTeachingPlanMonthDAO ctpmDAO = new CTeachingPlanMonthDAO();
			String monthThemeName = null;
			String executionDate = null;
			
			if(request.getParameter("MonthThemeName") != null && !request.getParameter("MonthThemeName").equals("")){
				monthThemeName = request.getParameter("MonthThemeName");
			}
			if(request.getParameter("ExecutionDate") != null && !request.getParameter("ExecutionDate").equals("")){
				executionDate = request.getParameter("ExecutionDate");
				
			}
		
			try {
				request.setAttribute("pageNo", 1);
				int PageSize = Utility.PageSize;
				ArrayList al = ctpmDAO.getSearchCondition(monthThemeName, executionDate, teacherID);
				int totalPage = 0;
				if (al.size() % PageSize == 0) {
					totalPage = al.size()/PageSize;
					request.setAttribute("totalPage",totalPage);
				} else {
					totalPage = (al.size()/PageSize) + 1;
					request.setAttribute("totalPage",totalPage);
				}
		
				al = new ArrayList<CollectivityTeachingPlanMonth>();
				ListIterator<CollectivityTeachingPlanMonth> it = ctpmDAO.getSearchCondition(monthThemeName, executionDate, teacherID).listIterator();
				int ii = 0;
				while (it.hasNext()) {
					CollectivityTeachingPlanMonth t = it.next();
					
					ctpm = new CollectivityTeachingPlanMonth();
					ctpm.setCMonthArrangeID(t.getCMonthArrangeID());
					ctpm.setMonthThemeName(t.getMonthThemeName());
					ctpm.setConstitutor(t.getConstitutor());
					ctpm.setClassID(t.getClassID());
					ctpm.setPushDateStart(t.getPushDateStart());
					ctpm.setPushDateEnd(t.getPushDateEnd());
					
					al.add(ctpm);
					ii++;
		
					if(ii > (PageSize-1)) {
						break;
					}
				}
				request.setAttribute("CTPMList", al);	
			} catch (SQLException e) {
				e.printStackTrace();
			}	
			request.getRequestDispatcher("../" + Utility.JSP_CTeachingPlanMonthInfo).forward(request, response);
		} else if (strFunc.equals("CTPMNetworkMore")) {
			String strCMonthArrangeID = request.getParameter("CMonthArrangeID");
			int intWeekID = Integer.parseInt(request.getParameter("WeekID"));
			int intActivityOptionSize = Integer.parseInt(request.getParameter("ActivityOptionSize"));
			String strActivityOptionName = request.getParameter("ActivityOptionName");
			strActivityOptionName = new String(strActivityOptionName.getBytes("iso-8859-1"),"utf-8"); 
			CWeekArrangeDAO cwaDAO = new CWeekArrangeDAO();
			CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
			CMonthWeekAimDAO cmwaDAO = new CMonthWeekAimDAO();
			CTeachingPlanMonthDAO ctpmDAO = new CTeachingPlanMonthDAO();
			try {
				
				int weekID = intWeekID;
				List<TopicTransferModel> models = cwaDAO.queryTopicModels(cmwaDAO.getTPIDSSByCMonthArrangeID(strCMonthArrangeID, weekID));
				Map<Integer,List<String>> developmentDomainActivityMapping = new HashMap<Integer,List<String>>();
				for(TopicTransferModel t : models){
					List<String> temp = developmentDomainActivityMapping.get(t.getDevelopmentDomain());
					if(temp==null){
						developmentDomainActivityMapping.put(t.getDevelopmentDomain(), temp=new ArrayList<String>());
					}
					temp.add(t.getActiveName());
				}
				
				CollectivityTeachingPlanMonth ctpm = ctpmDAO.getCTPMNetByCMAID(strCMonthArrangeID);
				request.setAttribute("developmentDomainActivityMapping", developmentDomainActivityMapping);
				request.setAttribute("CTPMArr", ctpm);
				request.setAttribute("CMonthArrangeID", strCMonthArrangeID);
				request.setAttribute("IntWeekID", intWeekID);
				request.setAttribute("ActivityOptionSize", intActivityOptionSize);
				request.setAttribute("ActivityOptionName", strActivityOptionName);
				
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../" + Utility.JSP_CTPMNetworkMore).forward(request, response);
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	public void gotoCTPMInfo(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException{
		CollectivityTeachingPlanMonth ctpm = null;
		CTeachingPlanMonthDAO ctpmDAO = new CTeachingPlanMonthDAO();
		
		com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
		
		Integer teacherID = teacher.getTeacherId();
	
		try {
			request.setAttribute("pageNo", 1);
			int PageSize = Utility.PageSize;
			ArrayList al = ctpmDAO.getAllCTeachingPlanMonth(teacherID);
			int totalPage = 0;
			if (al.size() % PageSize == 0) {
				totalPage = al.size()/PageSize;
				request.setAttribute("totalPage",totalPage);
			} else {
				totalPage = (al.size()/PageSize) + 1;
				request.setAttribute("totalPage",totalPage);
			}
	
			al = new ArrayList<CollectivityTeachingPlanMonth>();
			ListIterator<CollectivityTeachingPlanMonth> it = ctpmDAO.getAllCTeachingPlanMonth(teacherID).listIterator();
			int ii = 0;
			while (it.hasNext()) {
				CollectivityTeachingPlanMonth t = it.next();
				
				ctpm = new CollectivityTeachingPlanMonth();
				ctpm.setCMonthArrangeID(t.getCMonthArrangeID());
				ctpm.setMonthThemeName(t.getMonthThemeName());
				ctpm.setConstitutor(t.getConstitutor());
				ctpm.setClassID(t.getClassID());
				ctpm.setPushDateStart(t.getPushDateStart());
				ctpm.setPushDateEnd(t.getPushDateEnd());
				
				al.add(ctpm);
				ii++;
	
				if(ii > (PageSize-1)) {
					break;
				}
			}
			request.setAttribute("CTPMList", al);	
		} catch (SQLException e) {
			e.printStackTrace();
		}	
	}

}
